import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/',
    component: () => import('@/layouts/BasicLayout.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '数据总览', icon: 'DashboardOutlined' }
      },
      {
        path: 'category',
        name: 'Category',
        component: () => import('@/views/Category.vue'),
        meta: { title: '分类管理', icon: 'AppstoreOutlined' }
      },
      {
        path: 'teacher',
        name: 'Teacher',
        component: () => import('@/views/Teacher.vue'),
        meta: { title: '教员管理', icon: 'TeamOutlined' }
      },
      {
        path: 'teacher/audit',
        name: 'TeacherAudit',
        component: () => import('@/views/TeacherAudit.vue'),
        meta: { title: '教员审核', icon: 'AuditOutlined' }
      },
      {
        path: 'parent',
        name: 'Parent',
        component: () => import('@/views/Parent.vue'),
        meta: { title: '家长管理', icon: 'UserOutlined' }
      },
      {
        path: 'article',
        name: 'Article',
        component: () => import('@/views/Article.vue'),
        meta: { title: '资讯管理', icon: 'FileTextOutlined' }
      },
      {
        path: 'feedback',
        name: 'Feedback',
        component: () => import('@/views/Feedback.vue'),
        meta: { title: '反馈处理', icon: 'MessageOutlined' }
      },
      {
        path: 'order',
        name: 'Order',
        component: () => import('@/views/Order.vue'),
        meta: { title: '订单管理', icon: 'ShoppingOutlined' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const token = userStore.token

  if (to.path !== '/login' && !token) {
    next('/login')
  } else if (to.path === '/login' && token) {
    next('/')
  } else {
    next()
  }
})

export default router

